package com.breakfast.fun.ui.user.login;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.data.entity.user.UserData;
import com.breakfast.fun.event.FinishEvent;
import com.breakfast.fun.ui.user.UserFragment;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.SharedUtil;
import com.breakfast.fun.util.T;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.sdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

public class LoginActivity extends BaseActivity<LoginPresenter, LoginModel> implements LoginContract.View {


    @Bind(R.id.iv_login_back)
    ImageView mIvLoginBack;
    @Bind(R.id.rb_login_code)
    RadioButton mRbLoginCode;
    @Bind(R.id.rb_login_pwd)
    RadioButton mRbLoginPwd;
    @Bind(R.id.rg_login)
    RadioGroup mRgLogin;
    @Bind(R.id.et_login_mobile_by_code)
    EditText mEtLoginMobileByCode;
    @Bind(R.id.tv_login_code)
    TextView mTvLoginCode;
    @Bind(R.id.et_login_pwd_by_code)
    EditText mEtLoginPwdByCode;
    @Bind(R.id.ll_login_by_code)
    LinearLayout mLlLoginByCode;
    @Bind(R.id.et_login_mobile_by_pwd)
    EditText mEtLoginMobileByPwd;
    @Bind(R.id.et_login_pwd_by_pwd)
    EditText mEtLoginPwdByPwd;
    @Bind(R.id.ll_login_by_pwd)
    LinearLayout mLlLoginByPwd;
    @Bind(R.id.btn_login)
    Button mBtnLogin;
    @Bind(R.id.tv_login_register)
    TextView mTvLoginRegister;
    @Bind(R.id.tv_login_forget)
    TextView mTvLoginForget;
    private int time = 60;
    private Timer timer = new Timer();
    private TimerTask task;

    private int loginType = 0;
    private static final int LOGIN_BY_CODE = 0;
    private static final int LOGIN_BY_PWD = 1;


    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, Constant.WX_ID, false);


//        AssetManager assertMgr = context.getAssets();
//        Typeface font = Typeface.createFromAsset(assertMgr, "fonts/applefont.ttf");
//        mRbLoginCode.setTypeface(font);
//        mRbLoginPwd.setTypeface(font);
//        mEtLoginMobileByCode.setTypeface(font);
//        mEtLoginPwdByCode.setTypeface(font);
        setListener();
        EventBus.getDefault().register(this);
    }

    private void setListener() {
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (loginType == LOGIN_BY_PWD && !TextUtils.isEmpty(mEtLoginMobileByPwd.getText().toString().trim())
                        && !TextUtils.isEmpty(mEtLoginPwdByPwd.getText().toString().trim())) {
                    presenter.loginByPwd(mEtLoginMobileByPwd.getText().toString().trim(), mEtLoginPwdByPwd.getText().toString().trim());
                    return;
                }
                if (loginType == LOGIN_BY_CODE && !TextUtils.isEmpty(mEtLoginPwdByCode.getText().toString().trim())
                        && !TextUtils.isEmpty(mEtLoginMobileByCode.getText().toString().trim())) {
                    presenter.loginByCode(mEtLoginMobileByCode.getText().toString().trim(), mEtLoginPwdByCode.getText().toString().trim());
                    return;
                }
                Toast.makeText(getApplicationContext(), "信息不完整，请检查一下！", Toast.LENGTH_LONG).show();
            }
        });

        mTvLoginForget.setOnClickListener(v -> {
            Intent intent = new Intent(context, ForgetActivity.class);
            startActivity(intent);
        });

        mTvLoginRegister.setOnClickListener(v -> {
            Intent intent = new Intent(context, RegisterActivity.class);
            startActivity(intent);
        });


        mEtLoginMobileByCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s) || s.length() < 11) {
                    mTvLoginCode.setBackgroundResource(R.color.gray_silver);
                    mTvLoginCode.setClickable(false);
                    mEtLoginPwdByCode.setEnabled(false);
                } else if (!TextUtils.isEmpty(s) || s.length() == 11) {
                    mTvLoginCode.setBackgroundResource(R.drawable.selector_btn);
                    mTvLoginCode.setClickable(true);
                    mEtLoginPwdByCode.setEnabled(true);
                }
            }
        });

//        btnWeixinLogin.setOnClickListener(v -> {
//            // 将该app注册到微信
//            api.registerApp(Constant.WX_ID);
//            loginByWeixin();
//        });

        mRgLogin.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (checkedId == mRbLoginCode.getId()) {
                    mLlLoginByCode.setVisibility(View.VISIBLE);
                    mLlLoginByPwd.setVisibility(View.GONE);
                    loginType = LOGIN_BY_CODE;
                } else if (checkedId == mRbLoginPwd.getId()) {
                    mLlLoginByCode.setVisibility(View.GONE);
                    mLlLoginByPwd.setVisibility(View.VISIBLE);
                    loginType = LOGIN_BY_PWD;
                }
            }
        });


        mTvLoginCode.setOnClickListener(v -> {
            presenter.getLoginCode(mEtLoginMobileByCode.getText().toString());

        });


        mIvLoginBack.setOnClickListener(v -> {
            finish();
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    class SendMessage extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected Integer doInBackground(Integer... params) {

            return 1;
        }

        @Override
        protected void onPostExecute(Integer result) {
            mTvLoginCode.setEnabled(false);
            mTvLoginCode.setBackgroundResource(R.color.gray_silver);
            task = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() { // UI thread
                        @Override
                        public void run() {
                            if (time <= 0) {
                                // 当倒计时小余=0时记得还原图片，可以点击
                                mTvLoginCode.setEnabled(true);
                                mTvLoginCode.setBackgroundResource(R.drawable.selector_btn);
                                mTvLoginCode.setTextColor(Color.WHITE);
                                mTvLoginCode.setText("获取验证码");
                                task.cancel();
                            } else {
                                if (mTvLoginCode == null) {
                                    return;
                                }
                                mTvLoginCode.setText(time + "秒后重试");
                                mTvLoginCode.setTextColor(Color.rgb(125, 125, 125));
                            }
                            time--;
                        }
                    });
                }
            };

            time = 60;
            timer.schedule(task, 0, 1000);
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void loginSuccess(UserData userData) {
//        T.show("登录成功");
        SharedUtil.putString(context, "user", new Gson().toJson(userData));
        SharedUtil.putString(context, "sign", userData.getUserSign());
        Constant.setUserSign(userData.getUserSign());
        Constant.setUserData(userData);
        setUserAlias();
        UserFragment.isNeedRefesh = true;
        LoginActivity.this.finish();
    }

    private void setUserAlias() {
        //// TODO: 2016/8/24
        //设置极光推送
    }

    @Override
    public void loginFailure() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void saveRecommendCode(String code) {
        SharedUtil.putString(context, "recommendCode", code);
    }

    @Override
    public void sendCodeSuccess() {
        T.show("发送成功");
        new SendMessage().execute();
    }

    @Override
    public void openGiftActivity() {
        Intent intent = new Intent(this, GiftActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        EventBus.getDefault().post(new FinishEvent("LoginActivity"));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventFinish(FinishEvent event) {
        if (event.getActivityName().equals(getClass().getSimpleName())) {
            this.finish();
        }
    }

    private String genNonceStr() {
        //Random r = new Random(System.currentTimeMillis());
        //return MD5.getMessageDigest((APP_ID + r.nextInt(10000) + System.currentTimeMillis()).getBytes());
        return "noncestr";
    }

    private String genTimestamp() {
        //return System.currentTimeMillis() + "";
        return "timestamp";
    }


    private void loginByWeixin() {
        // send oauth request
        final SendAuth.Req req = new SendAuth.Req();
        final SendAuth.Resp resp = new SendAuth.Resp();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo";
        api.sendReq(req);
    }

    private void goToShowMsg(ShowMessageFromWX.Req showReq) {
        WXMediaMessage wxMsg = showReq.message;
        WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;

        StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
        msg.append("description: ");
        msg.append(wxMsg.description);
        msg.append("\n");
        msg.append("extInfo: ");
        msg.append(obj.extInfo);
        msg.append("\n");
        msg.append("filePath: ");
        msg.append(obj.filePath);

        L.d("title:" + wxMsg.title + ",msg:" + msg.toString() + ",thumbData:" + wxMsg.thumbData);
    }

    @Override
    public void finish() {
        if (task != null) {
            task.cancel();
        }
        super.finish();
    }
}
